﻿using System.Collections.Generic;
using System.Linq;
using BattleFury.Lib;
using BattleFury.Lib.Bots;
using BattleFury.Lib.GameEvents;
using BattleFury.Lib.ServerPlayer;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using BattleFury.Lib.Extensions;
using System;

namespace RyanBots
{
    public class RyanBot1 : Bot
    {
        private readonly Random _r = new Random();

        public RyanBot1(long Id)
            : base(Id)
        {
            Tint = Color.Orange;
        }

        public override void LoadContent()
        {
            Texture = RenderEngine.Get().Content.Load<Texture2D>(@".\gfx\Characters\Character001");
            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            if (CurrentMovement == null )
            {
                Move(new Movement(Position, new Vector2(Position.X + _r.Next(-50, 50), Position.Y + _r.Next(-50, 50))));
            }
            else if (ArePlayersNearby())
            {
                GenericPlayer closePlayer = GetNearestPlayer();
                if (!closePlayer.Position.Distance(Position).Approx(200, 5))
                {
                    if (closePlayer.Position.Distance(Position) > 200)
                        Move(new Movement(Position, closePlayer.Position));
                    else
                        Move(new Movement(Position, new Vector2(0, 0)));

                }
                else
                    Move(new Movement(Position, Position));
            }

            if (CurrentMovement.IsMoving)
                AdvanceKeyFrame();
        }


        private GenericPlayer GetNearestPlayer()
        {
            if (nearbyPlayers != null && nearbyPlayers.Count > 0)
                return (from a in nearbyPlayers
                        select a).OrderBy(c =>
                            (System.Math.Abs(c.Position.X) - System.Math.Abs(Position.X)) +
                            (System.Math.Abs(c.Position.Y) - System.Math.Abs(Position.Y))
                        ).First();
            throw new System.NotImplementedException();
        }

        private List<GenericPlayer> nearbyPlayers;

        private bool ArePlayersNearby()
        {
            if (GetVisiblePlayersHandler == null)
                return false;

            nearbyPlayers = GetVisiblePlayersHandler(this);
            return nearbyPlayers.Count > 0;
        }

    }
}
